package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.converter.CartItemConverterImpl;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.form.CheckAllItemRequest;
import com.cskaoyan.shopping.service.ICartService;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author Austin Hsu
 * @Date 2022/9/20 22:36
 */

@Service
public class ICartServiceImpl implements ICartService {


    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartItemConverter cartItemConverter;



    /**
     * 获得购物车商品列表
     */
    @Override
    public List<CartProductDto> getCartListById(Long userId) {


        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);
        //1.配置Redis Config对象 2.使用single模式和地址 3.用这个配置创建客户端并向redis-server发起请求

        Map<String, CartProductDto> redissonClientMap = redissonClient.getMap(userId.toString());   //得到userId=1 的HashMap

        List<CartProductDto> list = new ArrayList<>();
        for (Map.Entry<String, CartProductDto> stringCartEntry : redissonClientMap.entrySet()) {  //HashMap的结构ProductId={该商品的Json字符串}
            list.add(stringCartEntry.getValue());
        }

        return list;
    }

    /**
     * 添加商品到购物车
     *
     * @param request
     * @return
     */
    @Override
    public void addToCart(CartRequest request) {               //这里重新起一个Redis会不会到别的数据库里去
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);

        Long pid = request.getProductId();                       //给mySQL用
        String productId = request.getProductId().toString();    //给Redis用
        Integer addProductNum = request.getProductNum();

        Map<String, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());  //从Redis里拿到这个用户id的Map
        //----------------------------购物车里已经加过这个商品---------------------------------------
        for (Map.Entry<String, CartProductDto> stringCartDtoEntry : map.entrySet()) {             //map存的是 productId -- 购物车对象
            if (productId.equals(stringCartDtoEntry.getKey() )) {               //匹配到购物车里添加过这类商品
                CartProductDto cartProductDto = map.get(productId);
                Long amount = cartProductDto.getProductNum() + addProductNum;  //应该不用转long把 会自动
                cartProductDto.setProductNum(amount);
                map.put(productId, cartProductDto);       //?????这里会自动把redis里的覆盖掉吗？
                return;
            }
        }
        //----------------------------购物车里没有加过这个商品---------------------------------------
        CartProductDto cartProductDto = itemMapper.selectItemByProductId(pid);

//        Item item=itemMapper.selectByPrimaryKey(pid);                        // PO
//        CartProductDto cartProductDto1 = cartItemConverter.item2Dto(item);   // 用转换器也可以

        String imgUrl = cartProductDto.getProductImg();         //所有的图片连接（以逗号分割）

        if (imgUrl.contains(",")){                                //如果有多张图
            String imgUrlSolo = imgUrl.substring(0, imgUrl.indexOf(","));                                     //首图
            cartProductDto.setProductImg(imgUrlSolo);
        }


        cartProductDto.setProductNum(Long.valueOf(addProductNum));
        cartProductDto.setChecked("true");
        map.put(productId, cartProductDto);

        return;


    }

    @Override
    public void updateCartNum(CartRequest request) {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);

        String productId = request.getProductId().toString();    //给Redis用
        Integer productNum = request.getProductNum();         //这里不是add 而是直接修改数量
        String checked = request.getChecked();

        Map<String, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());  //从Redis里拿到这个用户id的Map
        //----------------------------购物车里已经加过这个商品---------------------------------------
        for (Map.Entry<String, CartProductDto> stringCartDtoEntry : map.entrySet()) {             //map存的是 productId -- 购物车对象
            if (stringCartDtoEntry.getKey().equals(productId)) {               //匹配到购物车里添加过这类商品
                CartProductDto cartProductDto = map.get(productId);
                cartProductDto.setProductNum(Long.valueOf(productNum));
                cartProductDto.setChecked(checked);
                map.put(productId, cartProductDto);       //?????这里会自动把redis里的覆盖掉吗？
                return;
            }
        }
    }

    @Override
    public void checkAllCartItem(CheckAllItemRequest request) {  //把redis里所有对象的checker改为true或者false
        String checked = request.getChecked();        //全部置为这个true或者false

        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);

        Map<String, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
        for (Map.Entry<String, CartProductDto> stringCartDtoEntry : map.entrySet()) {             //map存的是 productId -- 购物车对象
            stringCartDtoEntry.getValue().setChecked(checked);
        }

    }

    @Override
    public void deleteCartItem(Long uid, Long itemId) {
        //Redis里删
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);

        Map<String, CartProductDto> map = redissonClient.getMap(uid.toString());  //从Redis里拿到这个用户id的Map

        map.remove(itemId.toString());

    }


    @Override
    public void deleteCheckedItem(Long userId) {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);

        Map<String, CartProductDto> map = redissonClient.getMap(userId.toString());  //从Redis里拿到这个用户id的Map


        for (Map.Entry<String, CartProductDto> stringCartDtoEntry : map.entrySet()) {
            if ("true".equals(stringCartDtoEntry.getValue().getChecked())) {         //遍历、如果CartProductDto对象里的checked属性为true则删除
                map.remove(stringCartDtoEntry.getKey());                        //把这个productId的键值对删掉
            }
        }


    }
}
